package jhunter.security;

import jhunter.rt.conf.ext.ActionExt;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PermissionCheck {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	private final WildcardPermission[] anonActionNames = new WildcardPermission[] { new WildcardPermission("action:*:login:login"),
			new WildcardPermission("action:*:login:loginSubmit"), 
			new WildcardPermission("action:*:login:loginOut")};

	public boolean isPermitted(ActionExt action) {

		Subject currentUser = SecurityUtils.getSubject();
		for (WildcardPermission anon : anonActionNames) {
			Permission a = action.getPermission();
			if (anon.implies(a)) {
				log.debug("anonymous action access {}", a.toString());
				return true;
			}
		}
		if (currentUser.isPermitted(action.getPermission())) {
			// Permitted
			return true;
		}
		return false;
	}

}
